import { getCartListAPI, postCartListAPI, deleteCartListAPI, getCartCheckedAPI } from '@/api/index.js'
export default {
  // 开启命名空间
  namespaced: true,
  state: {
    cartInfoList: []
  },
  mutations: {
    GETCARTLIST(state, data) {
      state.cartInfoList = data
    }
  },
  actions: {
    // 获取购物车列表
    async getCartList({ commit }) {
      const data = await getCartListAPI()
      commit('GETCARTLIST', (data.length && data[0].cartInfoList) || [])
    },
    // 添加到购物车(对已有物品进行数量改动)
    async postCartList({ commit }, { skuId, skuNum }) {
      await postCartListAPI(skuId, skuNum)
    },
    // 删除商品从购物车
    async deleteCartList({ commit }, skuId) {
      await deleteCartListAPI(skuId)
    },
    // 切换商品选中状态
    async getCartChecked({ commit }, { skuID, isChecked }) {
      await getCartCheckedAPI(skuID, isChecked)
    },
    // 切换所有商品选中状态
    getAllCartChecked({ dispatch, state }, isChecked) {
      const promiseArr = []
      state.cartInfoList.forEach(item => {
        if (item.isChecked === isChecked) return
        promiseArr.push(dispatch('getCartChecked', { skuID: item.skuId, isChecked }))
      })
      // Promise.all()  等所有异步请求发送完，并返回结果后
      return Promise.all(promiseArr)
    },
    deletecheckedgoods({ dispatch, state }) {
      const promiseArr = []
      state.cartInfoList.forEach((item) => {
        if (item.isChecked === 1) {
          promiseArr.push(dispatch('deleteCartList', item.skuId))
        }
      })
      return Promise.all(promiseArr)
    }
  },
  getters: {

  }
}
